#pragma once
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <string>
#include <iostream>
#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_runner
{
    using namespace ns_util;
    using namespace ns_log;
    class Runner
    {
    public:
        Runner()
        {
        }
        ~Runner()
        {
        }
        static void SetProcLimet(int _cpu_limit, int _mem_limit)
        {
            // 设置 CPU
            struct rlimit rcpulimit;
            rcpulimit.rlim_max = RLIM_INFINITY;
            rcpulimit.rlim_cur = _cpu_limit;
            setrlimit(RLIMIT_CPU, &rcpulimit);

            // 设置内存 
            struct rlimit rmemlimit;
            rmemlimit.rlim_max = RLIM_INFINITY;
            rmemlimit.rlim_cur = _mem_limit * 1024 * 1024; // 转化为 KB
            setrlimit(RLIMIT_AS, &rmemlimit);
        }
        static int Run(const std::string &file_name, int cpu_limit, int mem_limit)
        {

            int _stdinfd = open(PathUtil::Stdin(file_name).c_str(), O_CREAT | O_WRONLY, 777);
            int _stdoutfd = open(PathUtil::Stdout(file_name).c_str(), O_CREAT | O_WRONLY, 777);
            int _stderrfd = open(PathUtil::Stderr(file_name).c_str(), O_CREAT | O_WRONLY, 777);

            if (_stdinfd < 0 || _stdoutfd < 0 || _stderrfd < 0)
            {
                LOG(ERROR) << "打开文件失败" << "\n";
                return -1;
            }
            pid_t pid = fork();
            if (pid < 0)
            {
                close(_stdinfd);
                close(_stdoutfd);
                close(_stderrfd);
                LOG(ERROR) << "创建子进程失败 " << "\n";
                return -2;
            }
            else if (pid == 0)
            {
                dup2(_stdinfd, 0);
                dup2(_stdoutfd, 1);
                dup2(_stderrfd, 2);
                SetProcLimet(cpu_limit, mem_limit);
                execl(PathUtil::Exe(file_name).c_str(), PathUtil::Exe(file_name).c_str(), nullptr);
                exit(1);
            }
            else
            {
                close(_stdinfd);
                close(_stdoutfd);
                close(_stderrfd);
                int status = 0;
                LOG(INFO) << "运行成功" << "\n";
                waitpid(pid, &status, 0);
                return status & 0x7F; // 如果返回大于 0, 则说明收到了信号, 运行出错
            }
        }
    };
}